<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input placeholder="请输入SPU名称" v-model="SpuParmas.name"></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select placeholder="请选择" v-model="SpuParmas.tmid" style="width: 240px">
                    <el-option v-for="(item) in spuTrademarkLsit" :key="item.id" :label="item.name" :value="item.id"></el-option>   
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input
                    v-model="SpuParmas.description"
                    :rows="5"
                    type="textarea"
                    placeholder="输入描述"
                ></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload
                    v-model:file-list="skuImageLsit"
                    action="http://localhost:3000/api/source/Image/updatetradeMarkImage"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :before-upload="handleUpload"
                >
                    <el-icon><Plus/></el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible"  >
                    <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;"/>
                </el-dialog>
            </el-form-item>
            <el-form-item label="SPU属性">
                <!-- 展示销售属性下拉菜单 -->
                <el-select v-model="saleAttrNameAndId" :placeholder="unSelectSaleAttr?.length?`还未选择${unSelectSaleAttr.length}个`:'无'"  style="width: 240px" >
                    <el-option :value="`${item.id}:${item.name}`" v-for="(item) in unSelectSaleAttr" :key="item.id" :label="item.name"></el-option>
                </el-select>
                <el-button @click="addSaleAttr" :disabled="saleAttrNameAndId?false:true" type="primary" icon="Plus" style="margin-left: 10px;">新增销售属性</el-button>
                <!-- table展示销售属性与销售值得地方 -->
                <el-table style="margin-top: 10px;" border :data="skuSaleAttrList">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名" width="120px" prop="saleAttrName">
                    </el-table-column>
                    <el-table-column label="属性值">
                        <template #="{row}">
                            <el-tag style="margin: 0 5px;" @close="row.spuSaleAttrValueList.splice(index,1)" v-for="(tag,index) in row.spuSaleAttrValueList" :key="tag.id" closable>
                                {{ tag.saleAttrValueName }}
                            </el-tag>
                            <el-input v-model="row.saleAttrValue" @blur="inputView(row)" v-if="row.flag==true" size="small" placeholder="请输入属性值" style="width: 100px;"></el-input>
                            <el-button v-else @click="toEdit(row)" style="margin: 0 5px;" type="primary" size="small" icon="Plus"></el-button>
                            
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{$index}">
                            <el-button type="danger" size="small" icon="Delete" @click="skuSaleAttrList?.splice($index,1) "></el-button>
                        </template>
                        
                    </el-table-column>
               </el-table>
            </el-form-item>
            <el-form-item>
                <el-button @click="save" type="primary" >保存</el-button>
                <el-button @click="cancel" type="primary">取消</el-button>
            </el-form-item>

        </el-form>
    </div>
</template>

<script setup lang='ts'>
import {ref,computed } from 'vue';
import {reqSpuTradeMaek,reqSkuImage,reqSpuHasSaleAttr,reqBaseSaleAttr,AddOrUpdateSaleAttr} from '@/api/product/spu/index';
import type {BaseSaleAttr,SaleAttr,skuImageData,spuData,spuTradeMarkResponseData,skuImageResponseData,SaleAttrResponseData,BaseSaleAttrData,TradeMarkDatadata} from '@/api/product/spu/type'

import { ElMessage } from 'element-plus';
//存储对应三级分类的全部品牌的数据
const spuTrademarkLsit=ref<TradeMarkDatadata>()
//存储对应sku图片数据
const skuImageLsit=ref<skuImageData[]>()
//存储对应sku属性数据
const skuSaleAttrList=ref<SaleAttr[]>()
//存储全部的属性
const allAttrList=ref<BaseSaleAttr[]>()
//存储新增修改的发送请求数据
const SpuParmas=ref<spuData>({
    id:'',
    name:'',
    description:'',
    parentId:0,
    tmid:'',
    spuSaleAttrList:[],
    spuImageList:[]
    
})
//图片预览对话框显隐
const dialogVisible=ref<boolean>(false)
//图片预览对话框显示图片的地址
const dialogImageUrl=ref<string>('')
//收集在下拉框添加的属性
const saleAttrNameAndId=ref<string>('')

const $emit=defineEmits(['changeScene'])

//子组件spuForm绑定的
const cancel=()=>{
    $emit('changeScene',{flag:0,parmas:'update'})
    
}
//发送请求
const getSpuAttr=async (row:spuData)=>{
    SpuParmas.value=row
    //获取对应三级分类的全部品牌的数据
    const result:spuTradeMarkResponseData=await reqSpuTradeMaek(row.parentId)
    spuTrademarkLsit.value=result.data

    //获取对应sku图片数据
    const result1:skuImageResponseData=await reqSkuImage((row.id as number))
    skuImageLsit.value=result1.data.map(item=>{
        return {
            url:item.imgUrl,
            name:item.imgName
        }
    })
    //获取对应sku属性数据
    const result2:SaleAttrResponseData=await reqSpuHasSaleAttr((row.id as number))
    skuSaleAttrList.value=result2.data
    //获取全部的属性
    const result3:BaseSaleAttrData=await reqBaseSaleAttr()
    allAttrList.value=result3.data
      
}
//图片预览按钮
const handlePictureCardPreview=(file:skuImageData)=>{
    dialogVisible.value=true
    dialogImageUrl.value=file.url as string
   
}
//图片删除按钮
const handleRemove=()=>{ 
}
//图片上传之前的回调,约束文件类型和大小
const handleUpload=(file:any)=>{
    if(file.type==="image/png"||file.type==="image/jpeg"||file.type==="image/gif"){
        if(file.size/1024/1024<4){
            ElMessage({
                type:'success',
                message:'上传成功'
            })
            return true
        }
        ElMessage({
            type:'error',
            message:'文件大小需小于4M'
        })
        return false
    }
    else{
        ElMessage({
            type:'error',
            message:'文件格式需image/png或image/jpeg或image/gif'
        })
        return false
    }
    
}

//计算当前SPU还未拥有的属性
let unSelectSaleAttr=computed(()=>{
    //全部属性：版本、颜色、尺码
    //已有的属性：版本、颜色
    
    let unSelectArr=allAttrList.value?.filter((item:BaseSaleAttr)=>{
        // 使用 ?? [] 确保空数组作为默认值
        return skuSaleAttrList.value?.every((item1:SaleAttr)=>{
            return item.name!=item1.saleAttrName
        })
    })
    
    return unSelectArr
})

//添加属性按钮
const addSaleAttr=()=>{
    /* baseSaleAttrId:number,
       saleAttrName:string,
       spuSaleAttrValueList:SpuSaleAttrValueList
    */
    const [baseSaleAttrId,saleAttrName]=saleAttrNameAndId.value.split(":")
    let newSaleAttr:SaleAttr= {
        baseSaleAttrId:baseSaleAttrId,
        saleAttrName:saleAttrName,
        spuSaleAttrValueList:[]
    }
    skuSaleAttrList.value?.push(newSaleAttr)
    //清空下拉框选择
    saleAttrNameAndId.value=''  
}

//属性值按钮的点击事件
const toEdit=(row:SaleAttr)=>{
    //按钮隐藏，输入框显示
    row.flag=true
    //用于存储输入框内的内容
    row.saleAttrValue=''
}
//属性值输入框的焦点事件
const inputView=(row:SaleAttr)=>{
    //输入框隐藏，按钮显示
    row.flag=false
    // 非法情况一
    if(row.saleAttrValue?.trim()==''){
        ElMessage({
            type:'error',
            message:'属性值不能为空'
        })
        return 
    }
    const {baseSaleAttrId,saleAttrValue}=row
    //非法情况二
    let repeat=row.spuSaleAttrValueList.find((item)=>{
        return item.saleAttrValueName==saleAttrValue
    })
    if(repeat){
        ElMessage({
            type:'error',
            message:'属性值不能重复'
        })
        return
    }
    //判断之后再添加
    row.spuSaleAttrValueList.push({
        baseSaleAttrId,
        saleAttrValueName:(saleAttrValue as string)
    })

     
}
//保存按钮
const save=async()=>{
    //整理参数到SpuParmas用于发送请求
    // 1、整理图片参数
    SpuParmas.value.spuImageList=(skuImageLsit.value as skuImageData[]).map((item)=>{
        const obj={
            imgName:'',
            imgUrl:''
        }
        if(!item.response){
            obj.imgName=(item.name as string)
            obj.imgUrl=(item.url as string)
             
        }else{   
            obj.imgName=item.response.url.split("=")[1]
            obj.imgUrl=item.response.url
           
        }
        return obj
    })


    
    //2、整理属性参数
    SpuParmas.value.spuSaleAttrList=(skuSaleAttrList.value as SaleAttr[])
    
    //发送请求修改|增加SPU属性
    const result:any = await AddOrUpdateSaleAttr(SpuParmas.value)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:SpuParmas.value.id?'更新成功':'添加成功'
        })
        //切换场景，回到属性
        $emit('changeScene',{flag:0,parmars:SpuParmas.value.id?'update':'add'})
    }else{
        ElMessage({
            type:'error',
            message:SpuParmas.value.id?'更新失败':'添加失败'
        })
    }
    
    
    //成功
    //失败
}
//父组件点击添加调用
const initAddAttr=async(categroy3Id:number)=>{
    //清空之前的填写
    Object.assign(SpuParmas.value,{
        id:'',
        name:'',
        description:'',
        parentId:0,
        tmid:'',
        spuSaleAttrList:[],
        spuImageList:[]
        
    })
    //清空照片
    skuImageLsit.value=[]
    // 清空属性
    skuSaleAttrList.value=[]
    //获取三级分类id
    SpuParmas.value.parentId=categroy3Id
    saleAttrNameAndId.value=''
    //获取对应三级分类的全部品牌的数据
    const result:spuTradeMarkResponseData=await reqSpuTradeMaek(categroy3Id)
    spuTrademarkLsit.value=result.data
    //获取全部的属性
    const result1:BaseSaleAttrData=await reqBaseSaleAttr()
    allAttrList.value=result1.data



    
}
//子组件方法需对外暴露
defineExpose({getSpuAttr,initAddAttr})

</script>

<style scoped lang='scss'>

</style>